package com.epalmpay.service.spot.impl;

import com.epalmpay.dto.order.OrderInDTO;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.PayBalanceChange;
import com.epalmpay.payplat.TkRefund;
import com.epalmpay.payplat.result.RefundResult;
import com.epalmpay.service.posapi.PosApiServiceTransactional;
import com.epalmpay.service.spot.ISpotService;
import com.epalmpay.status.Rescode;
import com.epalmpay.util.*;
import com.epalmpay.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/24.
 */
@Service("spotService")
public class SpotServiceImpl implements ISpotService {

    @Resource
    private TradeOfflineMapper tradeOfflineMapper;

    @Resource
    private OrderServiceGoodMapper orderServiceGoodMapper;
    @Resource
    private OrderServiceGoodDetailMapper orderServiceGoodDetailMapper;

    @Resource
    private PosApiServiceTransactional posApiServiceTransactional;

    @Autowired
    private TicketMapper ticketMapper;

    @Autowired
    private RefundPasswordMapper refundPasswordMapper;
    
    @Resource
	private MemberMapper memberMapper;
    @Resource
	private StatisMemberMapper statisMemberMapper;


    @Override
    public List<Ticket> selectTicketsByGroupId(Ticket ticket) {
        return ticketMapper.selectAll(ticket);
    }

    @Override
    public int insertTicket(Ticket ticket) {
        return ticketMapper.insertTicket(ticket);
    }

    @Override
    public Ticket selectTicketById(Ticket ticket) {
        return ticketMapper.selectTicketById(ticket);
    }

    @Override
    public int updateTicket(Ticket ticket) {
        return ticketMapper.updateTicket(ticket);
    }

    @Override
    public int deleteTicket(Ticket ticket) {
        return ticketMapper.deleteTicket(ticket);
    }

    @Override
    public Ticket selectTicketByName(Ticket ticket) {
        return ticketMapper.selectTicketByName(ticket);
    }

    @Override
    public void insertTicketTrade(TradeOffline to) {

    }

    @Override
    public Boolean saveSpotData(OrderInDTO orderInDTO) {
        OrderServiceGood orderServiceGood=orderServiceGoodMapper.selectByOrderNo(orderInDTO.getOrderNo());
        if(orderServiceGood==null){
        	return false;
        }
        OrderServiceGoodDetail orderServiceGoodDetail=orderServiceGoodDetailMapper.queryByTickets(orderServiceGood.getId());
        if(orderServiceGoodDetail==null){
        	return false;
        }
        orderServiceGood.setTickName(orderInDTO.getTickName());//门票名称多个用/隔开
        orderServiceGood.setNumber(orderInDTO.getTickets().shortValue());
        orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);
        
        orderServiceGoodDetail.setOperator(orderInDTO.getOperator());
        orderServiceGoodDetail.setCouponCode(orderInDTO.getCouponCode());//生成券码
        orderServiceGoodDetailMapper.updateByPrimaryKeySelective(orderServiceGoodDetail);
		return true; 
    }

    /**
     * 门票核销
     * @param couponCode
     * @return
     * @throws ApplicationException
     */
    @Transactional
    public Response couponVerify(String couponCode) throws ApplicationException, ParseException {
        Map<String, Object> map = new HashMap<String, Object>();


        OrderServiceGoodDetail orderServiceGoodDetail = orderServiceGoodDetailMapper.queryGoodOrderNo(couponCode);
        if(orderServiceGoodDetail ==null){
            return Response.getError("券码不存在");
        }


      /*  String beginTime = DateUtil.fomatDate(new Date(), DateUtil.sdfDay);
        String  endTime = DateUtil.fomatDate(orderServiceGoodDetail.getValidDate(), DateUtil.sdfDay);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date bt = sdf.parse(beginTime);
        Date et=sdf.parse(endTime);
        if(et.before(bt)) {
            return Response.getError("已过了可核销时间");
        }*/

        Date date = new Date();

        OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());

//        short usedNumber = orderServiceGood.getUsedNumber() == null ? 0 : orderServiceGood.getUsedNumber();
//        if( ++usedNumber == orderServiceGood.getNumber()) {
            orderServiceGood.setAllVerifyTime(date);
            orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.OrderFinished.getType());
//        }
        orderServiceGood.setUsedNumber(orderServiceGood.getNumber());
        map.put("number",orderServiceGood.getNumber());
        map.put("tickName",orderServiceGood.getTickName());




        //券码详情记录更新
        orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.Verified.getType());
        orderServiceGoodDetail.setVerifyTime(date);
        orderServiceGoodDetail.setGmtModified(date);

        PayBalanceChange payBalanceChange = null;
        TradeOffline tradeOffline = null;
        try {
            posApiServiceTransactional.saveDoCouponVerify(orderServiceGood, orderServiceGoodDetail, payBalanceChange, tradeOffline);

        } catch (Exception e) {
            e.printStackTrace();
            return Response.getError("服务器处理错误)");
        }

        return Response.getSuccess(map);
    }

    @Override
    public void updateRefundTicket(TradeOffline to) throws Exception {
        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderIdStatus(to.getOrderId(),(byte)1);
        TkRefund tkRefund = null;
        if(tradeOffline.getPayType() == 1) {//支付宝
            tkRefund = TkRefund.initialize("ALIPAY", tradeOffline.getMerchantNo(), tradeOffline.getOrderId(), tradeOffline.getRealAmount() + "",
                    tradeOffline.getRealAmount() + "", tradeOffline.getTerminalNo());
        } else if(tradeOffline.getPayType() == 3) {//微信
            tkRefund = TkRefund.initialize("WECHAT", tradeOffline.getMerchantNo(), tradeOffline.getOrderId(), tradeOffline.getRealAmount() + "",
                    tradeOffline.getRealAmount() + "", tradeOffline.getTerminalNo());
        }
            //修改服务订单状态
            OrderServiceGood oosg = orderServiceGoodMapper.selectByOrderNo(to.getOrderId());
            OrderServiceGood osg = new OrderServiceGood();
            osg.setId(oosg.getId());
            osg.setOrderStatus(5);
            orderServiceGoodMapper.updateByPrimaryKeySelective(osg);
            //修改服务商品券码状态
            OrderServiceGoodDetail oosgd = orderServiceGoodDetailMapper.selectByOrderId(oosg.getId());
            OrderServiceGoodDetail osgd = new OrderServiceGoodDetail();
            osgd.setId(oosgd.getId());
            osgd.setCouponStatus(4);
            orderServiceGoodDetailMapper.updateByPrimaryKeySelective(osgd);

            //修改订单状态
            TradeOffline newto = new TradeOffline();
            newto.setOrderId(tradeOffline.getOrderId());
            newto.setTransactionStatus((byte) BizEnum.TransactionStatus.ISRefund.getType());
            tradeOfflineMapper.updateByOrderIdSelective(newto);
            RefundResult payResult = IPayAPI.finishTkRefund(tkRefund);
            if (!payResult.getResult_code().equals("000000")) {
                throw new ApplicationException(Rescode.FAIL, "退款调用失败" + payResult.getResult_msg());
            }
            
            
            
            //退款成功 更新会员的消费总额跟消费次数
            if(tradeOffline.getPayerId()!=null){
            	memberMapper.updateMemberUpdateAmount(tradeOffline.getPayerId(),tradeOffline.getRealAmount());
        		statisMemberMapper.updateMemberCostomerInfo(tradeOffline.getPayerId(),tradeOffline.getRealAmount());
            }
    		
        
    }

    @Override
    public void updateRefundPassword(RefundPassword rp) {
        refundPasswordMapper.updateRefundPassword(rp);
    }

    @Override
    public RefundPassword selectRefundById(RefundPassword rp) {
        return refundPasswordMapper.selectRefundById(rp);
    }
}
